package com.hfy.pcberpbackend.controller;

import com.hfy.pcberpbackend.service.QuoteService;
import com.hfy.pcberpbackend.dto.*;
import com.hfy.pcberpbackend.common.Result;
import com.hfy.pcberpbackend.common.PageResult;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.Map;
import java.util.HashMap;

/**
 * 报价单Controller
 */
@Slf4j
@RestController
@RequestMapping("/api/quotes")
@RequiredArgsConstructor
@Validated
public class QuoteController {
    
    private final QuoteService quoteService;
    
    /**
     * 获取报价单列表
     */
    @GetMapping
    public Result<PageResult<QuoteVO>> getQuoteList(QuoteQueryDTO query) {
        log.info("获取报价单列表，查询条件：{}", query);
        
        try {
            PageResult<QuoteVO> result = quoteService.getQuotePage(query);
            return Result.success("获取成功", result);
        } catch (Exception e) {
            log.error("获取报价单列表失败", e);
            return Result.error("获取报价单列表失败：" + e.getMessage());
        }
    }
    
    /**
     * 获取报价记录列表
     */
    @GetMapping("/records")
    public Result<PageResult<QuoteVO>> getQuoteRecordList(QuoteQueryDTO query) {
        log.info("获取报价记录列表，查询条件：{}", query);
        
        try {
            PageResult<QuoteVO> result = quoteService.getQuoteRecordPage(query);
            return Result.success("获取成功", result);
        } catch (Exception e) {
            log.error("获取报价记录列表失败", e);
            return Result.error("获取报价记录列表失败：" + e.getMessage());
        }
    }
    
    /**
     * 根据ID获取报价单详情
     */
    @GetMapping("/{id}")
    public Result<QuoteVO> getQuoteById(@PathVariable Long id) {
        log.info("根据ID获取报价单详情，ID：{}", id);
        
        try {
            QuoteVO quote = quoteService.getQuoteById(id);
            return Result.success("获取成功", quote);
        } catch (RuntimeException e) {
            log.error("获取报价单详情失败", e);
            return Result.notFound(e.getMessage());
        } catch (Exception e) {
            log.error("获取报价单详情失败", e);
            return Result.error("获取报价单详情失败：" + e.getMessage());
        }
    }
    
    /**
     * 新增报价单（草稿状态）
     */
    @PostMapping
    public Result<Map<String, Object>> createQuote(@Valid @RequestBody QuoteCreateDTO createDTO) {
        log.info("新增报价单：{}", createDTO);
        
        try {
            // TODO: 从请求上下文或认证信息中获取操作人
            String operator = "system"; // 临时使用系统用户
            
            Long id = quoteService.createQuote(createDTO, operator);
            
            Map<String, Object> result = new HashMap<>();
            result.put("id", id);
            result.put("quoteCode", quoteService.generateQuoteCode());
            
            return Result.success("新增成功", result);
        } catch (RuntimeException e) {
            log.error("新增报价单失败", e);
            return Result.badRequest(e.getMessage());
        } catch (Exception e) {
            log.error("新增报价单失败", e);
            return Result.error("新增报价单失败：" + e.getMessage());
        }
    }
    
    /**
     * 更新报价单
     */
    @PutMapping("/{id}")
    public Result<Void> updateQuote(@PathVariable Long id, @Valid @RequestBody QuoteCreateDTO updateDTO) {
        log.info("更新报价单，ID：{}，数据：{}", id, updateDTO);
        
        try {
            // TODO: 从请求上下文或认证信息中获取操作人
            String operator = "system"; // 临时使用系统用户
            
            QuoteUpdateDTO quoteUpdateDTO = new QuoteUpdateDTO();
            quoteUpdateDTO.setId(id);
            quoteUpdateDTO.setCustomerCode(updateDTO.getCustomerCode());
            quoteUpdateDTO.setSalesperson(updateDTO.getSalesperson());
            quoteUpdateDTO.setContractNumber(updateDTO.getContractNumber());
            quoteUpdateDTO.setOrderDate(updateDTO.getOrderDate());
            quoteUpdateDTO.setIsTaxIncluded(updateDTO.getIsTaxIncluded());
            quoteUpdateDTO.setPaymentMethod(updateDTO.getPaymentMethod());
            quoteUpdateDTO.setRemark(updateDTO.getRemark());
            quoteUpdateDTO.setItems(updateDTO.getItems());
            
            quoteService.updateQuote(quoteUpdateDTO, operator);
            return Result.success("更新成功");
        } catch (RuntimeException e) {
            log.error("更新报价单失败", e);
            return Result.badRequest(e.getMessage());
        } catch (Exception e) {
            log.error("更新报价单失败", e);
            return Result.error("更新报价单失败：" + e.getMessage());
        }
    }
    
    /**
     * 提交报价单
     */
    @PostMapping("/{id}/submit")
    public Result<Void> submitQuote(@PathVariable Long id) {
        log.info("提交报价单，ID：{}", id);
        
        try {
            // TODO: 从请求上下文或认证信息中获取操作人
            String operator = "system"; // 临时使用系统用户
            
            quoteService.submitQuote(id, operator);
            return Result.success("提交成功");
        } catch (RuntimeException e) {
            log.error("提交报价单失败", e);
            return Result.badRequest(e.getMessage());
        } catch (Exception e) {
            log.error("提交报价单失败", e);
            return Result.error("提交报价单失败：" + e.getMessage());
        }
    }
    
    /**
     * 批准报价单
     */
    @PostMapping("/{id}/approve")
    public Result<Void> approveQuote(@PathVariable Long id, @RequestBody(required = false) Map<String, String> params) {
        log.info("批准报价单，ID：{}", id);
        
        try {
            // TODO: 从请求上下文或认证信息中获取操作人
            String operator = "system"; // 临时使用系统用户
            String reason = params != null ? params.getOrDefault("reason", "批准报价单") : "批准报价单";
            
            quoteService.approveQuote(id, reason, operator);
            return Result.success("批准成功");
        } catch (RuntimeException e) {
            log.error("批准报价单失败", e);
            return Result.badRequest(e.getMessage());
        } catch (Exception e) {
            log.error("批准报价单失败", e);
            return Result.error("批准报价单失败：" + e.getMessage());
        }
    }
    
    /**
     * 拒绝报价单
     */
    @PostMapping("/{id}/reject")
    public Result<Void> rejectQuote(@PathVariable Long id, @RequestBody Map<String, String> params) {
        log.info("拒绝报价单，ID：{}", id);
        
        try {
            // TODO: 从请求上下文或认证信息中获取操作人
            String operator = "system"; // 临时使用系统用户
            String reason = params.getOrDefault("reason", "拒绝报价单");
            
            quoteService.rejectQuote(id, reason, operator);
            return Result.success("拒绝成功");
        } catch (RuntimeException e) {
            log.error("拒绝报价单失败", e);
            return Result.badRequest(e.getMessage());
        } catch (Exception e) {
            log.error("拒绝报价单失败", e);
            return Result.error("拒绝报价单失败：" + e.getMessage());
        }
    }
    
    /**
     * 删除报价单
     */
    @DeleteMapping("/{id}")
    public Result<Void> deleteQuote(@PathVariable Long id) {
        log.info("删除报价单，ID：{}", id);
        
        try {
            quoteService.deleteQuote(id);
            return Result.success("删除成功");
        } catch (RuntimeException e) {
            log.error("删除报价单失败", e);
            return Result.badRequest(e.getMessage());
        } catch (Exception e) {
            log.error("删除报价单失败", e);
            return Result.error("删除报价单失败：" + e.getMessage());
        }
    }
    
    /**
     * 批量删除报价单
     */
    @DeleteMapping("/batch")
    public Result<Void> batchDeleteQuotes(@Valid @RequestBody BatchDeleteDTO batchDeleteDTO) {
        log.info("批量删除报价单，IDs：{}", batchDeleteDTO.getIds());
        
        try {
            quoteService.batchDeleteQuotes(batchDeleteDTO.getIds());
            return Result.success("批量删除成功");
        } catch (RuntimeException e) {
            log.error("批量删除报价单失败", e);
            return Result.badRequest(e.getMessage());
        } catch (Exception e) {
            log.error("批量删除报价单失败", e);
            return Result.error("批量删除报价单失败：" + e.getMessage());
        }
    }
    
    /**
     * 复制报价单
     */
    @PostMapping("/{id}/copy")
    public Result<Map<String, Long>> copyQuote(@PathVariable Long id) {
        log.info("复制报价单，原ID：{}", id);
        
        try {
            // TODO: 从请求上下文或认证信息中获取操作人
            String operator = "system"; // 临时使用系统用户
            
            Long newId = quoteService.copyQuote(id, operator);
            Map<String, Long> result = new HashMap<>();
            result.put("id", newId);
            return Result.success("复制成功", result);
        } catch (RuntimeException e) {
            log.error("复制报价单失败", e);
            return Result.badRequest(e.getMessage());
        } catch (Exception e) {
            log.error("复制报价单失败", e);
            return Result.error("复制报价单失败：" + e.getMessage());
        }
    }
    
    /**
     * 导出报价单Excel
     */
    @GetMapping("/export")
    public Result<String> exportQuotes(QuoteQueryDTO query) {
        log.info("导出报价单Excel，查询条件：{}", query);
        
        try {
            // TODO: 实现Excel导出功能
            return Result.success("导出功能开发中");
        } catch (Exception e) {
            log.error("导出报价单Excel失败", e);
            return Result.error("导出报价单Excel失败：" + e.getMessage());
        }
    }
    
    /**
     * 生成报价单编号
     */
    @GetMapping("/generate-code")
    public Result<Map<String, String>> generateQuoteCode() {
        log.info("生成报价单编号");
        
        try {
            String quoteCode = quoteService.generateQuoteCode();
            Map<String, String> result = new HashMap<>();
            result.put("quoteCode", quoteCode);
            return Result.success("生成成功", result);
        } catch (Exception e) {
            log.error("生成报价单编号失败", e);
            return Result.error("生成报价单编号失败：" + e.getMessage());
        }
    }
}